<?php

if(!defined('DIR_VSCORE'))
	define('DIR_VSCORE', DIR_LIB.'VsCore'.DIR_SEP);

if(!defined('DIR_JUNONA'))
	define('DIR_JUNONA', DIR_LIB.'Junona'.DIR_SEP);

require_once(DIR_VSCORE.'vsmessagestack.php');

require_once(DIR_JUNONA.'junobjectsfactory.php');

/* CREATE VIEW Querys
$q = "CREATE VIEW `operators_work_totals` AS SELECT `operators_work`.`id` AS `id`, `operators`.`groups_id` AS `group_id`, `operators_work`.`operators_id` AS `operators_id`,
`models`.`id` AS `models_id`,
`operators`.`name` AS `operator_name`,`operators_work`.`operations_id` AS `operations_id`,`models`.`number` AS `model_number`,`models`.`name` AS `model_name`,`operations`.`operation_id` AS `operation_id`,`operations`.`operation_name` AS `operation_name`,`operators_work`.`price` AS `price`,`operators_work`.`count` AS `count`, ROUND(`operators_work`.`count` * `operators_work`.`price`, 2) AS `total`, `operators_work`.`date` AS `date` from (`operators_work` JOIN `operators` JOIN `operations` JOIN `models`) WHERE (`operators`.`id` = `operators_work`.`operators_id`) and (`operations`.`id` = `operators_work`.`operations_id`) and (`models`.`id` = `operations`.`model_id`)";

*/


class JunOperatorWork {

	static $_sqlTable = 'operators_work';

	private $_operator = NULL;

	// array(0=>operators_id, 1=>operations_id, 3=>date, 4=>count, 5=>price, )
	private $_operations = array();

	private $_total = 0;

	static function makeForAdd($opId, $date) {
		//self::$_sqlTable = 'operators_work';
		self::$_sqlTable = 'operators_work_totals';
		$item = new JunOperatorWork($opId, $date, $date, '');

		return $item;
	}
	//=============================================================================

	static function makeForView($opId, $minDate, $maxDate, $orderBy='', $groupBy='') {
		self::$_sqlTable = 'operators_work_totals';
		$item = new JunOperatorWork($opId, $minDate, $maxDate, $orderBy, $groupBy);

		return $item;
	}
	//==================================================================================

	private function __construct($operatorId, $minDate, $maxDate, $orderBy, $groupBy) {
		//$item = &self::__construct();	// ERROR
		$this->_operator = JunObjectsFactory::makeOperator($operatorId);

		if(self::$_sqlTable == 'operators_work_totals')
			$q = "SELECT *";
		else
			$q = "SELECT *";

		if($groupBy!='') {
			if($groupBy=='operation') {
				$q .= ", SUM(count) AS count, ROUND(SUM(price*count), 2) AS total"; //, AVG(price) AS price
			}

		}

		$q .= " FROM `".self::$_sqlTable."` WHERE `operators_id`=".$this->_operator->id();
		if($minDate == $maxDate)
			$q .= " AND `date`='".$minDate."'";
		else
			$q .= " AND `date`>='".$minDate."' AND `date`<='".$maxDate."'"; //  AND `count`!=0


		if(empty($orderBy) && empty($groupBy)) {
			//$q .= " ORDER BY `date`, CAST(model_number AS UNSIGNED), CAST(operation_id AS UNSIGNED)";
			$q .= " ORDER BY CAST(model_number AS UNSIGNED), model_name, CAST(operation_id AS UNSIGNED)"; // 

		}
		else if(empty($groupBy)){
			$q .= " ORDER BY `".$orderBy."`";
		}

		if($groupBy!='') {
			if($groupBy=='operation') {
				$q .= " GROUP BY `operations_id`  ORDER BY CAST(model_number AS UNSIGNED), model_name, CAST(operation_id AS UNSIGNED)";
			}

		}

		//echo $q; exit;

		$db = VsDatabase::Instance();
		$res = $db->query($q);

		while($row = mysql_fetch_object($res)) {
			$this->_total += $row->total;
			
			$newOp = array(	'unique_id'		=>($row->operators_id.'_'.$row->date.'_'.$row->id.'_'.$row->operations_id),
							'id'			=>$row->id,
							'group_id'		=>$row->group_id,
							'operators_id'	=>$row->operators_id,
							'models_id'		=>$row->models_id,
							'operations_id'	=>$row->operations_id,
							'model_number'	=>$row->model_number,
							'model_name'	=>$row->model_name,
							'operation_number'=>$row->operation_id,
							'operation_name'=>$row->operation_name,
							'date'			=>$row->date,
							'count'			=>$row->count,
							'price'			=>$row->price,
							'sub_total'		=>$row->total,
							'saved'			=>'TRUE');

			array_push($this->_operations, $newOp);
		}
	}
	//============================================================================

	function operator() { return $this->_operator; }
	function operatorId() { return $this->_operator->id(); }
	function operatorName() { return $this->_operator->name(); }

	function operations() { return $this->_operations; }
	function total() { return $this->_total; }
	//============================================================================

	function addOperation($operation, $count, $date) {
		/*
		foreach($this->_operations as $k => $op) {
			if(($op['operations_id']==$operation->id()) && ($op['date']==$date)) {
				$this->_operations[$k]['count'] = $op['count'] + $count;

				//echo $op['count'];
				//echo $this->_operations[$k]['count'];

				$this->updateCount($this->_operations[$k]);

				return 1;
			}
		}
		*/

		$newOp = array('operators_id'=>$this->_operator->id(), 'operations_id'=>$operation->id(), 'date'=>$date, 'count'=>$count, 'price'=>$operation->price(), 'saved'=>'FALSE');
		array_push($this->_operations, $newOp);

		return 0;
	}
	//==============================================================================

	function save() {
		$this->insert();
	}
	//=============================================================================

	private function insert() {
		if(!count($this->_operations))
			return;

		$authId = VsAuth::Instance()->id();

		self::$_sqlTable = 'operators_work';

		$q = "INSERT INTO `".self::$_sqlTable."`(`operators_id`, `operations_id`, `date`, `count`, `price`, `added_by`, `updated_by`, `added_at`, `updated_at`) VALUES";
		foreach($this->_operations as $k => $op) {
			if($op['saved']=='TRUE') {
				//$this->deleteOperation($this->_operator->id(), $op['operations_id'], $op['date']);

				//echo $op['count'];
				//echo $this->_operations[$k]['count'];

				//$this->updateCount($op);

				continue;
			}

			$q .= "('".$this->_operator->id()."', '".$op['operations_id']."', '".$op['date']."', '".$op['count']."', '".$op['price']."', '".$authId."', '".$authId."', NOW(), NOW()),";
		}
		$q = rtrim($q, ',');
		//$q = substr($q, 0, strlen($q)-1);
		//echo $q; exit;

		$db = VsDatabase::Instance();
		$db->query($q);
	}
	//=============================================================================

	private function update($op) {
		$q = "UPDATE `operators_work` SET `count`=".$op['count'].", `updated_by`=NOW() WHERE `operators_id`=".$this->_operator->id()." AND `operations_id`=".$op['operations_id']." AND `date`='".$op['date']."'";

		//echo $q; exit;

		$db = VsDatabase::Instance();
		$db->query($q);
	}
	//==================================================================================================================

	static function updateRow($uniqueId, $pData) {
		$id = explode('_', $uniqueId);
		//echo "<pre>"; die(var_dump($pData));
		$authId = VsAuth::Instance()->id();

		/*
			$id[0] - operator
			$id[1] - date
			$id[2] - id (belejka nomer)
			$id[3] - operation
		*/

		//$q = "UPDATE `operators_work` SET `operations_id`=".$pData['operation'].", `price`=".$pData['price'].", `count`=".$pData['count'].", `updated_by`=NOW() WHERE `operators_id`=".$id[0]." AND `date`='".$id[1]."' AND `id`=".$id[2]." AND `operations_id`=".$id[3]." ON DUPLICATE KEY INSERT INTO `operators_work` (`operators_id`, `operations_id`, `date`, `count`, `price`, `added_by`, `updated_by`) VALUES('".$id[0]."', '".$id[3]."', '".$id[1]."', '".$pData['count']."', '".$pData['price']."', NOW(), NOW())";


		if(($id[3]!=$pData['operation']) && ($pData['count']<1)) {
			$ms = VsMessageStack::Instance();
			$ms->add(__CLASS__, '���������� ���������', '�� ���� �� ������� ���������� �� ����� ��� , � �� �� �������� ������ �������� �� 0!!!');
			
			return false;
		}

		
		$db = VsDatabase::Instance();
		
		if($id[3]==$pData['operation']) {
			if($pData['count']<1) {
				$ret = self::deleteOperation($id[0], $id[1], $id[2], $id[3]);
				return $ret;
			}
			else {
				if($pData['price']) {
					$q = "UPDATE `operators_work` SET `operations_id`=".$pData['operation'].", `price`=".$pData['price'].", `count`=".$pData['count'].", updated_by=".$authId.", `updated_at`=NOW() WHERE `operators_id`=".$id[0]." AND `date`='".$id[1]."' AND `id`=".$id[2]." AND `operations_id`=".$id[3];
					$db->query($q);
					return mysql_affected_rows();
				}
				else {
					$ret = self::updateCount($id[0], $id[1], $id[2], $id[3], $pData['count']);
					return $ret;
				}
				
			}
		}

		//echo $pData['operation']; exit;

		// Smqna na operaciqta za tozi red v tablicata
		$q = "SELECT `id` FROM `operators_work` WHERE `operators_id`=".$id[0]." AND `date`='".$id[1]."' AND `operations_id`=".$pData['operation'];
		//echo $q."<br /><br />";
		$res = $db->query($q);

		/* Ako sa6testvuva novata operaciq v sa6testvuva6t Composite Primery Key
			Iztrivane na starata operaciq i 
			dobavqne na novata kato <Nova Belejka>
		*/
		if(mysql_num_rows($res)) {
			$ret = self::deleteOperation($id[0], $id[1], $id[2], $id[3]);

			$q = "INSERT INTO `operators_work` (`operators_id`, `operations_id`, `date`, `count`, `price`, `added_by`, `updated_by`, `added_at`, `updated_at`) VALUES('".$id[0]."', '".$pData['operation']."', '".$id[1]."', '".$pData['count']."', '".$pData['price']."', ".$authId.", ".$authId.", NOW(), NOW())";
		}
		else {
			$q = "UPDATE `operators_work` SET `operations_id`=".$pData['operation'].", `price`=".$pData['price'].", `count`=".$pData['count'].", updated_by=".$authId.", `updated_at`=NOW() WHERE `operators_id`=".$id[0]." AND `date`='".$id[1]."' AND `id`=".$id[2]." AND `operations_id`=".$id[3];
		}
		//echo $q;

		$db->query($q);

		return mysql_affected_rows();
	}
	//===============================================================================================================

	static function insertRow($uniqueId, $pData) 
	{
		$id = explode('_', $uniqueId);
		$authId = VsAuth::Instance()->id();
		
		$q = "INSERT INTO `".self::$_sqlTable."`(`operators_id`, `operations_id`, `date`, `count`, `price`, `added_by`, `updated_by`, `added_at`, `updated_at`) VALUES";
		$q .= "('".$id[0]."', '".$id[3]."', '".$id[1]."', '".$pData['count']."', '".$pData['price']."', '".$authId."', '".$authId."', NOW(), NOW())";
		
		$db = VsDatabase::Instance();
		$db->query($q);
	}
	
	private static function deleteOperation($operatorId, $date, $id, $operationId) {
		self::$_sqlTable = 'operators_work';

		$q = "DELETE FROM `".self::$_sqlTable."` WHERE `operators_id`=".$operatorId." AND `operations_id`=".$operationId." AND `date`='".$date."' AND `id`=".$id;

		//echo $q; exit;

		$db = VsDatabase::Instance();
		$db->query($q);

		return mysql_affected_rows();
	}
	//==============================================================================


	private static function updateCount($operatorId, $date, $id, $operationId, $count) {
		$authId = VsAuth::Instance()->id();

		$q = "UPDATE `operators_work` SET `count`=".$count.", `updated_by`=".$authId.", `updated_at`=NOW() WHERE `operators_id`=".$operatorId." AND `operations_id`=".$operationId." AND `date`='".$date."' AND `id`=".$id;

		//echo $q; exit;

		$db = VsDatabase::Instance();
		$db->query($q);

		return mysql_affected_rows();
	}
	//==================================================================================================================

	static function updatePrices($operationId, $minDate, $maxDate) {
		if($this->_id<1)
			return;

		$authId = VsAuth::Instance()->id();

		$q = "UPDATE `operators_work` SET price='".$this->_price."', updated_by=".$authId.", updated_at=NOW() WHERE operations_id=".$this->_id." AND date>=".$minDate." AND date<=".$maxDate;

		$db = VsDatabase::Instance();
		$db->query($q);
	}
	//=================================================================================================================

};

?>
